package com.lovo.order.config;

import com.alibaba.fastjson2.JSONObject;
import com.lovo.util.ResultTokenVo;
import com.lovo.util.Verifier;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class SysInterceptor implements HandlerInterceptor {
    long time=0;
    long endTime=0;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       time=System.currentTimeMillis();
        String token=  request.getHeader("token");
        //对token进行验证
        ResultTokenVo resultTokenVo= Verifier.verifierJwt(token);
        if(resultTokenVo.getTag()==1) {
            //把json字符串转换为json
            JSONObject jsonObject = JSONObject.parseObject(resultTokenVo.getJson());
            request.setAttribute("userName",jsonObject.get("userName"));
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }else {
           PrintWriter p=new PrintWriter("{'tag':'0'}");
           p.flush();
           p.close();
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
      endTime=System.currentTimeMillis();
        System.out.println(request.getServletPath()+"/运行时间:"+(endTime-time));
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
